package cn.wolfcode.p2p.business.service.impl;
import java.math.BigDecimal;
import java.util.Date;

import cn.wolfcode.p2p.base.domain.Account;
import cn.wolfcode.p2p.base.domain.LoginInfo;

import cn.wolfcode.p2p.base.domain.RealAuth;
import cn.wolfcode.p2p.base.service.IAccountService;
import cn.wolfcode.p2p.business.domain.BidRequest;
import cn.wolfcode.p2p.business.domain.CreditTransfer;
import cn.wolfcode.p2p.business.domain.PaymentScheduleDetail;
import cn.wolfcode.p2p.business.mapper.CreditTransferMapper;
import cn.wolfcode.p2p.business.mapper.PaymentScheduleDetailMapper;
import cn.wolfcode.p2p.business.query.CreditTransferQuery;
import cn.wolfcode.p2p.business.service.IAccountFlowService;
import cn.wolfcode.p2p.business.service.IBidRequestService;
import cn.wolfcode.p2p.business.service.ICreditTransferService;
import cn.wolfcode.p2p.util.AssertUtil;
import cn.wolfcode.p2p.util.Constants;
import cn.wolfcode.p2p.util.PageResult;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Transactional
@Service
public class CreditTransferServiceImpl implements ICreditTransferService {
        @Autowired
        private CreditTransferMapper creditTransferMapper;
        @Autowired
        private PaymentScheduleDetailMapper paymentScheduleDetailMapper;
        @Autowired
        private IBidRequestService bidRequestService;
        @Autowired
        private IAccountService accountService;
        @Autowired
        private IAccountFlowService accountFlowService;
        @Override
        public PageResult queryCanCreditTransfer(CreditTransferQuery qo) {
                 //先查出COunt,如果COUNT为0,返回空集合
                 int row = creditTransferMapper.selectCount(qo);
                 if(row==0){
                     return new PageResult(Collections.EMPTY_LIST,0,1,qo.getPageSize());
                 }
                 List<CreditTransfer> list =creditTransferMapper.query(qo);
                 return new PageResult(list,row,qo.getCurrentPage(),qo.getPageSize());
        }

        @Override
        public void creditTransfer(Long[] bidIds) {
                //判断参数
                AssertUtil.instance().isNotNull(bidIds,"参数错误!");
                //查出对应BIDId insert
                List<CreditTransfer> creditTransfers = creditTransferMapper.selectReadyCreditTransfer(bidIds, UserContext.getLoginInfo().getId());
                for (CreditTransfer creditTransfer : creditTransfers) {
                        creditTransfer.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);
                        creditTransfer.setTransFrom(UserContext.getLoginInfo());
                        creditTransfer.setPublishDate(new Date());
                        creditTransferMapper.insert(creditTransfer);
                }
                paymentScheduleDetailMapper.batchUpdateTransferState(bidIds, PaymentScheduleDetail.TANSFER_STATE_TRANSFERING);
        }

        @Override
        public PageResult queryMyTransfer(CreditTransferQuery qo) {
                 //先查出COunt,如果COUNT为0,返回空集合
                 int row = creditTransferMapper.selectMyTransferCount(qo);
                 if(row==0){
                     return new PageResult(Collections.EMPTY_LIST,0,1,qo.getPageSize());
                 }
                 List<CreditTransfer> list =creditTransferMapper.queryMyTransferList(qo);
                 return new PageResult(list,row,qo.getCurrentPage(),qo.getPageSize());
        }

        /**
         * 认购债券标
         * @param id
         */
        @Override
        public void subscribe(Long id) {
                //判断参数
                AssertUtil.instance().isNotNull(id,"参数异常!");
                //判断债券标的状态要处于转让中
                CreditTransfer ct = creditTransferMapper.selectByPrimaryKey(id);
                AssertUtil.instance().isFalse(ct.getBidRequestState()!=Constants.BIDREQUEST_STATE_BIDDING,"当前债权标不处于待购状态");
                //判断认购人不是转让人
                LoginInfo currentLoginInfo = UserContext.getLoginInfo();//认购人
                LoginInfo transFrom = ct.getTransFrom();//装让人
                AssertUtil.instance().isFalse(currentLoginInfo.getId().longValue()==transFrom.getId().longValue()
                        ,"不能认购自己发布的债权标");
                //认购人不能是借款人
                BidRequest br = bidRequestService.getById(ct.getBidRequestId());
                LoginInfo createUser = br.getCreateUser();//借款人
                AssertUtil.instance().isFalse(createUser.getId().longValue()==currentLoginInfo.getId().longValue()
                        ,"您是当前债权标的借款人!不能认购!");
                //认购人的可用余额大于等于债券认购金额
                Account currentAccount = accountService.getByid(currentLoginInfo.getId());//当前认购人的账户
                AssertUtil.instance().isFalse(currentAccount.getUsableAmount().compareTo(ct.getBidRequestAmount())<0
                        ,"钱不够啊!请充钱!");

                //执行认购
                //转让人 可用余额加,产生债权转让成功流水,待收本金利息减少,
                Account transferFromAccount = accountService.getByid(transFrom.getId());//装让人账户
                transferFromAccount.addUsableAmount(ct.getBidRequestAmount());
                transferFromAccount.setUnReceiveInterest(transferFromAccount.getUnReceiveInterest().subtract(ct.getRemainInterest()));
                transferFromAccount.setUnReceivePrincipal(transferFromAccount.getUnReceivePrincipal().subtract(ct.getBidRequestAmount()));
                accountService.update(transferFromAccount);
                accountFlowService.createCreditTransferSuccessFlow(transferFromAccount,ct.getBidRequestAmount());
                //认购人 可用余额减少,流水,待收本金利息增加
                currentAccount.subtractUsableAmount(ct.getBidRequestAmount());
                currentAccount.setUnReceivePrincipal(currentAccount.getUnReceivePrincipal().add(ct.getBidRequestAmount()));
                currentAccount.setUnReceiveInterest(currentAccount.getUnReceiveInterest().add(ct.getRemainInterest()));
                accountService.update(currentAccount);
                accountFlowService.createCreditTransferForSubscribeFlow(currentAccount,ct.getBidRequestAmount());
                //债权标修改状态为已认购
                //认购时间,认购人
                ct.setTransDate(new Date());
                ct.setTransTo(currentLoginInfo);
                ct.setBidRequestState(Constants.BIDREQUEST_STATE_PAYING_BACK);
                update(ct);

                //收购计划由转让人变更为认购人,修改标的状态为正常,可正常打包
                paymentScheduleDetailMapper.batchUpdateTransferState(new Long[]{ct.getId()},PaymentScheduleDetail.TANSFER_STATE_NORMAL);
                paymentScheduleDetailMapper.changeTransferFrom(ct.getBidId(),currentLoginInfo.getId());


        }

        public void update(CreditTransfer ct) {
                int i = creditTransferMapper.updateByPrimaryKey(ct);
                AssertUtil.instance().isFalse(i==0,"修改债权标信息错误!请联系客服!");
        }

        @Override
        public CreditTransfer getByBidIdAndFromLoginInfoIdAndState(Long bidId, Long toLoginInfoId, int bidrequestState) {
                return creditTransferMapper.getByBidIdAndFromLoginInfoIdAndState(bidId,toLoginInfoId,bidrequestState);
        }
}
